<template>
    <div>
        <div class="userInfo" v-if="user.job_status == 3 || user.job_status == 4">
            <div class="topBox">
                <div class="topTitle">
                    <img src="../../../assets/image/zxl/icon8.png" style="width: 18px;height: 18px;margin-right: 4px;">
                    <span>离职记录</span>
                </div>
                <div class="topBtn">
                    <div class="topBtnItem" @click="changeEdit" v-if="!is_edit">
                        编辑
                    </div>
                    <div class="topBtnItem2" @click="saveEdit" style="margin-right: 12px;" v-if="is_edit">
                        保存
                    </div>
                    <div class="topBtnItem" @click="is_edit = false" v-if="is_edit">
                        取消
                    </div>
                </div>
            </div>
            <el-form ref="ruleFormRef" :inline="true" label-position="right" label-width="150px" :model="user"
                :rules="rules" class="form-inline">
                <el-form-item class="formItem" label="离职日期：" prop="resign_time">
                    <span v-if="!is_edit">{{ user.resign_time }}</span>
                    <el-date-picker v-if="is_edit" v-model="user.resign_time" type="date" format="YYYY/MM/DD"
                        value-format="YYYY-MM-DD" placeholder="请选择离职日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item class="formItem" label="离职类型：" prop="resign_type">
                    <span v-if="!is_edit">{{ getNameByValue1(user.resign_type) }}</span>
                    <el-select v-if="is_edit" v-model="user.resign_type" placeholder="请选择离职类型" @change="changeReason">
                        <el-option v-for="item in quitTypeOptions" :key="item.value" :label="item.name"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item class="formItem" label="离职原因：" prop="resign_reason">
                    <span v-if="!is_edit">{{ getNameByValue2(user.resign_type, user.resign_reason) }}</span>
                    <el-select v-if="is_edit" v-model="user.resign_reason" placeholder="请选择离职原因">
                        <el-option v-for="item in quitReasonOption" :key="item.value" :label="item.name"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item class="formItem1" label="备注：" prop="resign_desc">
                    <span v-if="!is_edit">{{ user.resign_desc }}</span>
                    <el-input v-if="is_edit" v-model="user.resign_desc" :rows="2" type="textarea" placeholder="备注" />
                </el-form-item>
            </el-form>
        </div>
        <div class="userInfo" style="border-bottom: 0px solid #eaeaea;">
            <div class="topBox">
                <div class="topTitle">
                    <img src="../../../assets/image/zxl/icon7.png" style="width: 18px;height: 16px;margin-right: 4px;">
                    <span>离职资料</span>
                </div>
                <!-- <div class="topBtn">
                    <div class="topBtnItem1">
                        上传合同
                    </div>
                </div> -->
            </div>
            <div class="btnBox">
                <div style="flex: 1;">
                    <button :class="htIndex == 0 ? 'uploadBtn' : 'uploadBtn1'" style="margin-right: 24px;"
                        @click="setListOnline">
                        线上合同
                    </button>
                    <button :class="htIndex == 1 ? 'uploadBtn' : 'uploadBtn1'" @click="setListOffline">
                        线下合同
                    </button>
                </div>
                <button class="topBtnItem1" @click="open = true">
                    上传合同
                </button>
            </div>
            <div style="margin-left: 28px;" v-if="htIndex == 0">
                <el-table :data="tableData" height="250" class="custom-table" style="width: 100%;">
                    <el-table-column prop="task_name" label="合同名称" align="center" />
                    <el-table-column prop="type" label="合同类型" align="center">
                        <template #default="{ row }">
                            <span>离职资料</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="sign_time" label="签署时间" align="center" />
                    <el-table-column fixed="right" label="操作" align="center">
                        <template #default="{ row }">
                            <el-button link type="primary" size="large" @click.stop="lookFile(row)">
                                查看
                            </el-button>
                            <el-button link type="primary" size="large" @click.stop="downloadFile1(row)">
                                下载
                            </el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <img src="../../..//assets/image/zxl/noData.png" width="94" style="width: 94px;height: 86px;" />
                    </template>
                </el-table>
                <!-- <Pagination style="justify-content: end;" :total="total" :current-page="pageInfo.page"
                    :page-size="pageInfo.limit" @pagination-change="handlePaginationChange" /> -->
            </div>
            <div style="margin-left: 28px;" v-if="htIndex == 1">
                <el-table :data="tableData" height="250" class="custom-table" style="width: 100%;">
                    <el-table-column prop="filename" label="合同名称" align="center" />
                    <el-table-column prop="type" label="合同类型" align="center">
                        <template #default="{ row }">
                            <span>{{ row.type == 2 ? '离职资料' : '' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="create_time" label="上传时间" align="center" />
                    <el-table-column fixed="right" label="操作" align="center">
                        <template #default="{ row }">
                            <el-button link type="primary" size="small" @click.stop="downloadFile(row)">
                                下载
                            </el-button>
                            <el-button link type="primary" size="small" @click.stop="deleteFiles(row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <img src="../../..//assets/image/zxl/noData.png" width="94" style="width: 94px;height: 86px;" />
                    </template>
                </el-table>
                <!-- <Pagination style="justify-content: end;" :total="total" :current-page="pageInfo.page"
                    :page-size="pageInfo.limit" @pagination-change="handlePaginationChange" /> -->
            </div>
        </div>
        <el-dialog v-model="open" title="上传合同" width="646" :before-close="handleClose">
            <el-form ref="ruleFormRef1" label-position="right" label-width="150px" :model="htForm" class="form-inline"
                style="display: flex;align-items: center;">
                <el-form-item class="formItem2" label="选择上传文件：" height="160">
                    <el-upload ref="uploadBox" class="upload-demo" drag name="file" :auto-upload="false"
                        :data="{ id: user.id, type: 2 }" :headers="{ token: token }"
                        action="https://demo-api.niuyuwang.com/hr/user/save_file" :on-success="uploadFileSuccess"
                        :on-error="uploadFileFail" :before-upload="beforeAvatarUpload">
                        <img src="../../../assets/image/zxl/icon14.png" style="width: 32px;height: 32px;">
                        <div class="tip1">点击或拖拽上传</div>
                        <div class="tip2">文件格式：".xls", ".xlsx", ".doc", ".docx", ".pdf", ".zip", ".txt"</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="small" @click="open = false">取消</el-button>
                    <el-button type="primary" color="#01509f" size="small" @click="uploadFile">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, defineEmits } from '@/TUIKit/adapter-vue';
import type { FormInstance, FormRules, ElMessage, ElMessageBox, UploadProps } from 'element-plus'
import { getFileList, getOnlineFileList, deleteFile, resign_handle } from "@/api/xl";
const props = defineProps({
    user: {
        type: Object,
        default: () => ({}) // 对象/数组默认值需返回函数
    }
})
onMounted(() => {
    setTimeout(() => {
        getList()
    }, 1000)
});
interface RuleForm {
    resign_time: string
    resign_type: string
    resign_reason: string
    resign_desc: string

}

const htIndex = ref(0)
const emits = defineEmits(['updateData']);
const ruleFormRef = ref<FormInstance>()
const is_edit = ref(false)
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log(rawFile)
    if (rawFile.type !== 'application/vnd.ms-excel' && rawFile.type !== 'application/x-zip-compressed' && rawFile.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' && rawFile.type !== 'text/plain' && rawFile.type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' && rawFile.type !== 'application/msword' && rawFile.type !== 'application/pdf' && rawFile.type !== 'application/zip') {
        ElMessage.error('文件格式：".xls", ".xlsx", ".doc", ".docx", ".pdf", ".zip", ".txt"')
        return false
    }
    return true
}
const quitTypeOptions = ref([
    { value: '1', name: "主动离职" },
    { value: '2', name: "被动离职" },
]);

const quitReasonOption = ref(null);

const quitReasonOption1 = ref([
    { value: '1', name: "个人原因" },
    { value: '2', name: "家庭原因" },
    { value: '3', name: "职业发展原因" },
    { value: '4', name: "其他原因" },
]);

const quitReasonOption2 = ref([
    { value: '5', name: "协议解除" },
    { value: '6', name: "无法胜任工作" },
    { value: '7', name: "试用期未通过" },
    { value: '8', name: "严重违法违纪" },
    { value: '9', name: "经济性裁员" },
    { value: '10', name: "其他原因" },
]);

const getNameByValue1 = (id) => {
    const userValue1 = quitTypeOptions.value.find(item => item.value === id)
    return userValue1 ? userValue1.name : ''
}

const getNameByValue2 = (type, id) => {
    const userValue2 = ref(null)
    if (type == '1') {
        userValue2.value = quitReasonOption1.value.find(item => item.value === id)
    } else if (type == '2') {
        userValue2.value = quitReasonOption2.value.find(item => item.value === id)
    }
    return userValue2.value ? userValue2.value.name : ''
}

const changeReason = (value) => {
    console.log(value)
    if (props.user.resign_type == 1) {
        quitReasonOption.value = quitReasonOption1.value
    } else if (props.user.resign_type == 2) {
        quitReasonOption.value = quitReasonOption2.value
    } else {
        quitReasonOption.value = []
    }
    props.user.resign_reason = ''
}

const changeEdit = () => {
    is_edit.value = true
    if (props.user.resign_type == 1) {
        quitReasonOption.value = quitReasonOption1.value
    } else if (props.user.resign_type == 2) {
        quitReasonOption.value = quitReasonOption2.value
    } else {
        quitReasonOption.value = []
    }
}
const saveEdit = () => {
    ruleFormRef.value.validate(res => {
        if (res) {
            console.log("表单验证成功");
            resign_handle({
                id: props.user.id,
                resign_time: props.user.resign_time,
                resign_type: props.user.resign_type,
                resign_reason: props.user.resign_reason,
                resign_desc: props.user.resign_desc,
                job_status: props.user.job_status
            }).then(res => {
                ElMessage({
                    message: res.msg,
                    grouping: true,
                    type: "success",
                });
                is_edit.value = false
                emits('updateData');
            });
        } else {
            console.log("表单验证失败");
            return false;
        }
    });
}

const uploadBox = ref(null)
const open = ref(false)
const token = localStorage.getItem('token')
const htForm = ref(null)
const ruleFormRef1 = ref(null)
const tableData = ref([])
const total = ref(100)
const pageInfo = reactive({
    page: 2,
    limit: 10
})
const handlePaginationChange = ({ page, size }: { page: number; size: number }) => {
    pageInfo.page = page
    pageInfo.limit = size
}

const rules = reactive<FormRules<RuleForm>>({
    resign_time: [
        { required: true, message: '请选择离职时间', trigger: 'change' },
    ],
    resign_type: [
        { required: true, message: '请选择离职时类型', trigger: 'change' },
    ],
    resign_reason: [
        { required: true, message: '请选择离职原因', trigger: 'change' },
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
const handleClose = (done: () => void) => {
    done()
}

const uploadFile = () => {
    uploadBox.value!.submit();
}
const uploadFileSuccess = () => {
    ElMessage({
        message: '上传成功',
        grouping: true,
        type: "success",
    });
    uploadBox.value!.clearFiles()
    open.value = false;
    setTimeout(() => {
        getList()
    }, 500)
}
const uploadFileFail = () => {
    ElMessage({
        message: '上传失败',
        grouping: true,
        type: "success",
    });
    uploadBox.value!.clearFiles()
    open.value = false;
    setTimeout(() => {
        getList()
    }, 500)
}
const setListOnline = () => {
    htIndex.value = 0;
    getList()
}

const setListOffline = () => {
    htIndex.value = 1;
    getList()
}
const getList = () => {
    if (htIndex.value == 0) {
        getOnlineFileList({
            id: props.user.id,
            type: 5
        }).then(res => {
            tableData.value = res.data
        });
    } else if (htIndex.value == 1) {
        getFileList({
            id: props.user.id,
            type: 2
        }).then(res => {
            tableData.value = res.data
        });
    }
}
const downloadFile = (row) => {
    const url = row.url; // 替换为实际文件 URL
    const a = document.createElement('a');
    a.href = url;
    a.download = row.filename; // 自定义下载文件名
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
const downloadFile1 = (row) => {
    const url = row.downloadUrl; // 替换为实际文件 URL
    const a = document.createElement('a');
    a.href = url;
    a.download = row.filename; // 自定义下载文件名
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
const lookFile = (row) => {
    if(row.previewUrl){
        window.open(row.previewUrl, "_blank");
    }
}
const deleteFiles = (row) => {
    ElMessageBox.confirm("是否确定删除?", "操作提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "ExitConfirmButton",
    }).then((action: Action) => {
        if (action === "confirm") {
            deleteFile({
                id: row.id
            }).then(res => {
                ElMessage({
                    message: res.msg,
                    grouping: true,
                    type: "success",
                });
                getList()
            });
        }
    });
}
defineExpose({
    changeEdit
})
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__label {
    font-size: 16px;
    /* 设置你需要的字体大小 */
}

::v-deep .el-form-item__content * {
    font-size: 16px;
    /* 设置你需要的字体大小 */
}

.upload-demo {
    width: 450px;

    ::v-deep .el-upload-dragger {
        background-color: #f7f7f7;
        width: 458px;
        height: 160px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .el-upload-list {
        width: 450px !important;
    }

    .tip1 {
        color: #666;
        font-size: 14px;
    }

    .tip2 {
        color: #999;
        font-size: 14px;
    }
}

.userInfo {
    padding: 12px 0 31px 0;
    border-bottom: 1px solid #eaeaea;
    // display: flex;
    // flex-wrap: wrap;

    .form-inline {
        margin-top: 32px;
        // display: flex;
        // flex-wrap: wrap;
        padding: 0 17px;

        .formItem {
            width: 31%;
            margin-bottom: 40px;
        }

        .formItem1 {
            width: 31%;
        }

        .formItem2 {
            display: flex;
            align-items: center;
        }
    }

    .topBox {
        display: flex;
        align-items: center;

        .topTitle {
            display: flex;
            align-items: center;
            flex: 1;
            font-size: 16px;
            color: #01509f;
        }

        .topBtn {
            display: flex;
            align-items: center;

            .topBtnItem {
                cursor: pointer;
                width: 42px;
                height: 30px;
                color: #01509f;
                border: 1px solid #01509f;
                border-radius: 6px;
                text-align: center;
                line-height: 30px;
                font-size: 14px;
            }

            .topBtnItem2 {
                cursor: pointer;
                width: 42px;
                height: 30px;
                background-color: #01509f;
                color: #ffffff;
                border-radius: 6px;
                text-align: center;
                line-height: 30px;
                font-size: 14px;
            }

            .topBtnItem:hover {
                transform: scale(1) translateY(-2px) !important;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            }

            .topBtnItem2:hover {
                transform: scale(1) translateY(-2px) !important;
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            }
        }
    }

    .btnBox {
        display: flex;
        align-items: center;
        margin: 19px 0 16px 28px;

        .uploadBtn {
            background-color: transparent;
            color: #01509f;
            width: 100px;
            height: 30px;
            border: 1px solid #01509f;
            border-radius: 6px;
            text-align: center;
            line-height: 30px;
        }

        .uploadBtn1 {
            background-color: transparent;
            color: #999;
            width: 100px;
            height: 30px;
            border: 1px solid #999;
            border-radius: 6px;
            text-align: center;
            line-height: 30px;
            cursor: pointer;
        }

        .topBtnItem1 {
            cursor: pointer;
            background-color: #01509f;
            color: #fff;
            width: 86px;
            height: 30px;
            border: 0px solid #eaeaea;
            font-size: 14px;
            border-radius: 6px;
            text-align: center;
            line-height: 30px;
        }

        .topBtnItem1:hover {
            transform: scale(1) translateY(-2px) !important;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
    }

    .custom-table .el-table__header th {
        color: #666;
        font-size: 16px;
        font-weight: lighter;
    }
}
</style>
